package com.owulia.leetcode.num.stack;

import java.util.Deque;
import java.util.LinkedList;

public class Calculate {

    public static int calculate(String s) {
        Deque<Integer> ops = new LinkedList<>();
        ops.push(1);
        int sign = 1;

        int ret = 0;
        int n = s.length();
        int i = 0;
        while (i < n) {
            if (s.charAt(i) == ' ') {
                i++;
            } else if (s.charAt(i) == '+') {
                sign = ops.peek();
                i++;
            } else if (s.charAt(i) == '-') {
                sign = -ops.peek();
                i++;
            } else if (s.charAt(i) == '(') {
                ops.push(sign);
                i++;
            } else if (s.charAt(i) == ')') {
                ops.pop();
                i++;
            } else {
                long num = 0;
                while (i < n && Character.isDigit(s.charAt(i))) {
                    num = num * 10 + s.charAt(i) - '0';
                    i++;
                }
                ret += sign * num;
            }
        }
        return ret;
    }


    public static void main(String[] args) {
        System.out.print(ca("1-(-234   -(13-(-1+2))-(15+6)"));
    }


    public static int ca(String s) {
        int n = s.length();
        int[] signArray = new int[n];
        signArray[0] = 1;
        int signIndex = 0;
        int sign = 1;
        int ans = 0;
        for (int i = 0; i < n; i++) {
            char curr = s.charAt(i);
            if (Character.isDigit(curr)) {
                int num = curr - '0';
                while (i < n - 1 && Character.isDigit(s.charAt(i + 1))) {
                    i++;
                    num = num * 10 + s.charAt(i) - '0';
                }
                ans += sign * num;
            } else if (curr == '(') {
                signIndex++;
                signArray[signIndex] = sign;
            } else if (curr == ')') {
                signIndex--;
            } else if (curr == '-') {
                sign = -signArray[signIndex];
            } else if (curr == '+') {
                sign = signArray[signIndex];
            }
        }
        return ans;
    }


}
